package edu.tyut.game.ui.community

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.net.toUri
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.hutool.core.util.URLUtil
import com.google.gson.Gson
import edu.tyut.game.GameApplication
import edu.tyut.game.databinding.ActivityUpdatePostFriendCircleBinding
import edu.tyut.game.logic.model.FriendCircle
import edu.tyut.game.logic.network.ServiceCreator
import edu.tyut.game.utils.LogUtils
import edu.tyut.game.utils.StatusBarUtils
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File
import java.net.URLEncoder
import java.nio.charset.StandardCharsets

class UpdatePostFriendCircleActivity : AppCompatActivity() {

    private val tag = this::class.java.name
    private lateinit var binding: ActivityUpdatePostFriendCircleBinding
    private val viewModel by lazy {
        ViewModelProvider(this)[UpdatePostFriendCircleViewModel::class.java]
    }
    private val viewModelCommunity by lazy {
        ViewModelProvider(this)[CommunityViewModel::class.java]
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityUpdatePostFriendCircleBinding.inflate(layoutInflater)
        setContentView(binding.root)
        // 隐藏ActionBar
        // 状态栏透明
        StatusBarUtils.setTranslucentStatusBar(this)

        // 编辑朋友圈
        viewModel.resEditFriendCircle.observe(this){ res ->
            val isSuccess = res.getOrNull()
            if (isSuccess == true){
                LogUtils.d(tag, "朋友圈编辑成功")
            }
        }

        val gridLayoutManager = GridLayoutManager(this, 3, RecyclerView.VERTICAL, false)
        gridLayoutManager.orientation = RecyclerView.VERTICAL
        binding.images.layoutManager = gridLayoutManager

        // 首先加载数据
        val friendCircleOld = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            intent.getSerializableExtra("friendCircleOld", FriendCircle::class.java)
        }else{
            intent.getSerializableExtra("friendCircleOld")
        } as FriendCircle
        binding.content.setText(friendCircleOld.content)
        val gson = Gson()
        val imagesOld = gson.fromJson<List<String>>(friendCircleOld.images, List::class.java)
        val urisOld = mutableListOf<Uri>()
        for (image in imagesOld){
            val urlStr = "${ServiceCreator.BASE_URL}${image}"
            LogUtils.d(tag, "urlStr: $urlStr")
            urisOld.add(urlStr.toUri())
        }
        val adapterOld =
            PostImageViewAdapter(this@UpdatePostFriendCircleActivity, urisOld)
        binding.images.adapter = adapterOld

        // 更新数据
        val imageList = mutableListOf<Uri>()
        val pickMultipleMedia =
            registerForActivityResult(ActivityResultContracts.PickMultipleVisualMedia(9)) { uris ->
                // Callback is invoked after the user selects media items or closes the
                // photo picker.
                if (uris.isNotEmpty()) {
                    Log.d("PhotoPicker", "Number of items selected: ${uris.size}")
                    imageList.clear()
                    imageList.addAll(uris)
                    val adapter =
                        PostImageViewAdapter(this@UpdatePostFriendCircleActivity, imageList)
                    binding.images.adapter = adapter
                } else {
                    Log.d("PhotoPicker", "No media selected")
                }
            }

        binding.selectPic.setOnClickListener {
            pickMultipleMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
        }

        // 更新朋友圈
        binding.post.setOnClickListener {
            val uid = GameApplication.loginUser?.id ?: 1
            val username = GameApplication.loginUser?.username ?: "admin"
            val gender = GameApplication.loginUser?.gender ?: "男"
            val avatarPath = GameApplication.loginUser?.avatarPath
            val content = binding.content.text.toString().trim()
            if (content.isEmpty() || content.isBlank()) {
                Toast.makeText(this, "内容不能为空😊~", Toast.LENGTH_LONG).show()
                return@setOnClickListener
            }
            val friendCircle = FriendCircle(friendCircleOld.id, uid, username, gender, avatarPath ?: "/image/image.jpg", content, "", 0)
            updateFriendCircle(imageList, friendCircle)
        }

        // 取消发布朋友圈
        binding.cancel.setOnClickListener {
            this.onBackPressedDispatcher.onBackPressed()
        }
    }
    // 更新朋友圈
    private fun updateFriendCircle(files: List<Uri>, friendCircle: FriendCircle) {
        val builder = MultipartBody.Builder().setType(MultipartBody.FORM)
        for (file in files) {
            val inputStream = contentResolver.openInputStream(file)
            val requestFile: RequestBody =
                RequestBody.create(
                    MediaType.parse("image/*"),
                    inputStream!!.readBytes()
                ) // 图片文件不能超过2G
            val str = file.toString()
            var name = str.substring(str.lastIndexOf("/") + 1)
            if (!name.contains(".")) name = "$name.jpg"
            builder.addFormDataPart("files", name, requestFile)
            inputStream.close()
        }
        val gson = Gson()
        builder.addFormDataPart("content", gson.toJson(friendCircle))
        val parts = builder.build().parts()
        // TODO 发送朋友圈
        LogUtils.d(tag, "${gson.toJson(friendCircle)}: 更新朋友圈...")
        viewModel.editFriendCircle(parts)
        // 重新加载
        viewModelCommunity.queryFriendCircle("DESC")
        // 退出
        Toast.makeText(this, "更新朋友圈成功😊~", Toast.LENGTH_LONG).show()
        this.onBackPressedDispatcher.onBackPressed()
    }

    companion object {
        fun actionStart(context: Context, friendCircleOld: FriendCircle) {
            val intent = Intent(context, UpdatePostFriendCircleActivity::class.java)
            intent.putExtra("friendCircleOld", friendCircleOld)
            context.startActivity(intent)
        }
        private const val REQUEST_CODE = 0x000001
    }
}